﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TY.Utilities;
using CefSharp;
using CefSharp.WinForms;
using System.Threading;
using System.Data;
using System.Collections;
using Aspose.Cells;

namespace TY_Hoist.WinApp
{
    public class MyService
    {

        ChromiumWebBrowser webBrowser = null;
        static bool terminalSearchMark = false;
        public event Action<String> InitCameraEvent;
        public event Action ShowCameraEvent;
        public event Action HideCameraEvent;
        public event Action<string, int> StartRecordVideoEvent;
        public event Action StopRecordVideoEvent;
        public MyService(ChromiumWebBrowser _webBrowser)
        {
            webBrowser = _webBrowser;
        }
        public void InitCamera(string ip, IJavascriptCallback callBack)
        {
            InitCameraEvent?.Invoke(ip);
            callBack.ExecuteAsync("ok");
        }
        public void ShowCamera()
        {
            try
            {

                ShowCameraEvent?.Invoke();

            }
            catch (Exception)
            {

                throw;
            }
        }
        public void HideCamera()
        {
            try
            {

                HideCameraEvent?.Invoke();

            }
            catch (Exception)
            {

                throw;
            }
        }
        public void StartRecordVideo(string experimentId, int setpIndex)
        {
            StartRecordVideoEvent?.Invoke(experimentId, setpIndex);
        }
        public void StopRecordVideo()
        {
            try
            {

                StopRecordVideoEvent?.Invoke();

            }
            catch (Exception)
            {

                throw;
            }
        }
        public void OpenExplore(string experimentId, int setpIndex)
        {
            var videoPath = "";
            if (ConfigNoCacheHelper.AppSettings("VideoPath") == "")
            {
                videoPath = System.Windows.Forms.Application.StartupPath + @"\Resource\ExperimentVideo";
            }
            else
            {
                videoPath = ConfigNoCacheHelper.AppSettings("VideoPath");
            }
            if (setpIndex == 0)
            {
                videoPath = videoPath + string.Format(@"\{0}\", experimentId);
            }
            else
            {
                videoPath = videoPath + string.Format(@"\{0}\{1}", experimentId, setpIndex);
            }
            System.Diagnostics.Process.Start(videoPath);
        }
        public void StartSearchTerminal(IJavascriptCallback callback)
        {
            terminalSearchMark = true;
            var localIP = Utils.GetLocalIPAddress();
            var ipPrfix = localIP.Substring(0, localIP.LastIndexOf(".") + 1);
            Task.Factory.StartNew(new Action(() =>
            {
                List<string> macList = new List<string>();
                for (int i = 0; i < 255; i++)
                {
                    if (!terminalSearchMark)
                        return;

                    webBrowser.ExecuteScriptAsync(string.Format("updateSearchProgress({0})", (int)(((i + 1.0) / 255.0) * 100)));
                    string zhIP = ipPrfix + (i + 1);
                    var status = RequestHelper.HttpGet(string.Format("http://{0}:5555/status", zhIP), 260);
                    if (status != null)
                    {

                        var macAddress = RequestHelper.HttpGet(string.Format("http://{0}:5555/getMacAddress", zhIP));
                        if (!macList.Contains(macAddress))
                        {
                            macList.Add(macAddress);
                            webBrowser.ExecuteScriptAsync(string.Format("addTerminal('{0}','{1}','{2}')", status, zhIP, macAddress));
                        }

                    }
                }
                callback.ExecuteAsync("1");

            }));

        }
        public void StopSearchTerminal()
        {
            terminalSearchMark = false;
            Thread.Sleep(300);
        }

        public void ExportRecord(string json, string saveFileName, CefSharp.IJavascriptCallback result)
        {
            Aspose.Cells.WorkbookDesigner designer = new WorkbookDesigner();
            //excel模板的地址  
            designer.Open(System.Environment.CurrentDirectory + @"\Resources\ExcelTemplate\RecordTemp.xls");
            try
            {
                var ff = JSON.Decode(json).ToDictionary()["data"];
                var syxx = (JSON.Decode(json).ToDictionary()["data"]).ToDictionary();
                bool sxResult = true;
                List<DictionaryEntry> de = new List<DictionaryEntry>();
                de.Add(new DictionaryEntry("StartTime", syxx["start_time"].ToString()));
                de.Add(new DictionaryEntry("Sycl", syxx["material_name"].ToString()));
                de.Add(new DictionaryEntry("Symj", syxx["muju_type"].ToString()=="1"?"50cm模具":"100cm模具"));
                de.Add(new DictionaryEntry("Syjl", syxx["test_juli"].ToString()+"cm"));

                de.Add(new DictionaryEntry("StartFrame", syxx["start_frame"].ToString()));
                de.Add(new DictionaryEntry("EndFrame", syxx["end_frame"].ToString()));
                de.Add(new DictionaryEntry("HyStartTime", (Utils.ObjToInt(syxx["start_frame"],0)/1000.0).ToString()+"秒"));
                de.Add(new DictionaryEntry("HyEndTime", (Utils.ObjToInt(syxx["end_frame"], 0) / 1000.0).ToString() + "秒"));
                de.Add(new DictionaryEntry("Dhfs", syxx["dianhuo_type"].ToString()=="1"?"点火棒":"电引信头"));
                de.Add(new DictionaryEntry("Syjielun", syxx["result"].ToString()));
                de.Add(new DictionaryEntry("Syr", syxx["experiment_user_name"]));


                //designer.Workbook.Worksheets[0].Pictures.Add(11, 0, Utils.ImageToStream(Utils.GetSvgImage(imageList[1])));
                designer.Workbook.Worksheets[0].Pictures.Add(10, 0, System.Environment.CurrentDirectory + "/InterfaceServer/Resource/ExperimentTemp/" + syxx["experiment_id"].ToString()+"/startFrame.jpg",40,80);
                designer.Workbook.Worksheets[0].Pictures.Add(13, 0, System.Environment.CurrentDirectory + "/InterfaceServer/Resource/ExperimentTemp/" + syxx["experiment_id"].ToString() + "/endFrame.jpg", 40, 80);
                foreach (var item in de)
                {
                    designer.SetDataSource(item.Key.ToString(), item.Value);
                }
                designer.Process();//全自动赋值  
                designer.Workbook.Save(saveFileName, new XlsSaveOptions(SaveFormat.Xlsx));
                //designer.Workbook.Save(saveFileName.Replace(".xlsx", ".pdf"), new XlsSaveOptions(SaveFormat.Pdf));
                FileOpera.copyFile(new System.IO.FileInfo(System.Environment.CurrentDirectory + "/InterfaceServer/Resource/ExperimentTemp/" + syxx["experiment_id"].ToString() + "/CamVideo.avi"), saveFileName.Replace(".xlsx", ".avi"));
                designer = null;
                using (result)
                {
                    result.ExecuteAsync(JSON.Encode(Utils.ToMsg(ResultStatus.SUCCESS, "成功")));
                }
            }
            catch (Exception ex)
            {
                using (result)
                {
                    result.ExecuteAsync(JSON.Encode(Utils.ToMsg(ResultStatus.ERROR, ex.Message)));
                }
            }


        }
        public string GetSylx(string code)
        {
            switch (code)
            {
                case "1":
                    return "阶段一试验";
                case "2":
                    return "阶段二试验";
                default:
                    return "";
            }

        }
        public string GetSyxx(string code)
        {
            switch (code)
            {
                case "1":
                    return "爆炸";
                case "2":
                    return "燃烧";
                case "3":
                    return "明显变色";

                default:
                    return "无变化";

            }
        }
    }
    public class RrecordData
    {

        public string RecordTime { get; set; }
        public string TempValue { get; set; }
    }
}
